﻿using System;
using System.Net;
using System.Web;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Hammock;
using Hammock.Authentication.OAuth;
using System.Diagnostics;
using Hammock.Silverlight.Compat;
using System.Windows.Navigation;

namespace Tweet_for_Windows_Phone_7_Series.Helper
{
    public class OauthHelper
    {
        private string authority = @"https://api.twitter.com/oauth/";
        private const string ConsumerKey = "AeKD608GePKuIbyMLlQtA";
        private const string ConsumerSecret = "IXErMFzH4UJzlFe3nwJmWiCELSmbbYwLv05xACV5hxk";
        public string AuthUrl { get { return authority + "authorize"; } }
        private NavigationService _NavService;

        public OauthHelper(NavigationService NavService)
        {
            _NavService = NavService;
        }

        private string responsestring = string.Empty;

        public void request_token()
        {
            Hammock.RestClient c = new RestClient()
            {
                Authority = authority,
                HasElevatedPermissions = true,
                Credentials = new OAuthCredentials()
                {
                    Type = OAuthType.RequestToken,
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                }
            };

            RestRequest r = new RestRequest()
            {
                Path = "request_token",
            };
            RestCallback callback = new RestCallback(Callback);
            c.BeginRequest(r, new RestCallback(Callback));                       
        }
        private NameValueCollection parameters = new NameValueCollection();
        private void Callback(Hammock.RestRequest request, Hammock.RestResponse response, object userState)
        {
            var a = response.Content;
            Debug.WriteLine(a);


            foreach (string s in a.Split('&'))
            {
                parameters.Add(s.Split('=')[0], s.Split('=')[1]);
            }
            if (!string.IsNullOrEmpty(parameters["oauth_token"]))
                _NavService.Navigate(new Uri(string.Format("/PageAuthorize.xaml?token={0}", parameters["oauth_token"]), UriKind.Relative));
        }
    }
}
